package com.aofei.pangu.interceptor;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;

import com.aofei.pangu.api.AccountApiService;
import com.aofei.pangu.ui.login.LoginActivity;
import com.aofei.pangu.utils.RetrofitClient;
import com.aofei.pangu.utils.TokenManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

import me.goldze.mvvmhabit.authorization.Token;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.utils.SPUtils;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Call;

public class TokenInterceptor implements Interceptor {


    private  Context mContext;



    public TokenInterceptor(Context mContext) {

        this.mContext = mContext;
    }

    @Override
    public Response intercept(final Chain chain) throws IOException {

        Request request = chain.request();
        Response originalResponse = chain.proceed(request);
        ResponseBody responseBody = originalResponse.body();

        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE);
        Buffer buffer = source.buffer();
        Charset charset = Charset.forName("utf8");;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(Charset.forName("utf8"));
        }
        String bodyStr = buffer.clone().readString(charset);
        Gson gson = new Gson();
        Type type = new TypeToken<BaseResponse<Token> >() {}.getType();
        BaseResponse<Token> httpResult = gson.fromJson(bodyStr,type);

        if(httpResult.getCode() == 401){

            Call<BaseResponse<Token>> call =  RetrofitClient.getInstance().create(AccountApiService.class)
                    .refreshToken(TokenManager.getRefreshToken());

            retrofit2.Response<BaseResponse<Token>> response = call.clone().execute();//刷新token必须使用同步请求

            BaseResponse<Token> refreshToken = response.body();

            if(refreshToken.isOk()){
                Token tokenInfo = response.body().getBody();
                TokenManager.setToken(tokenInfo);
                Request newRequest=request.newBuilder().header("Authorization", TokenManager.getAccessToken()).build();//重新拼装请求头
                return chain.proceed(newRequest);//重试request
            }else{

                mContext.startActivity(new Intent(mContext,LoginActivity.class));
                return originalResponse;
            }
        }else{
            return originalResponse;
        }
    }
}
